package com.ifreshwing.https;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import java.security.KeyStore;

public class HttpClientFactory {
	private static final String CHARSET = HTTP.UTF_8;
	private static HttpClient customerHttpClient = null;
	private static final int DEFAULT_MAX_CONNECTIONS = 20;
	private static final int DEFAULT_SOCKET_TIMEOUT = 30 * 1000;
	private static final int DEFAULT_CONNECT_TIMEOUT = 30 * 1000;

	private static int maxConnections = DEFAULT_MAX_CONNECTIONS;
	private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
	private static int connectTimeout = DEFAULT_CONNECT_TIMEOUT;

	private HttpClientFactory() {
	}

	public static synchronized HttpClient getHttpClient() {
		if (customerHttpClient == null) {
			HttpParams params = new BasicHttpParams();

			ConnManagerParams.setTimeout(params, socketTimeout);
			ConnManagerParams.setMaxConnectionsPerRoute(params,
					new ConnPerRouteBean(maxConnections));
			ConnManagerParams.setMaxTotalConnections(params,
					DEFAULT_MAX_CONNECTIONS);
			HttpConnectionParams.setSoTimeout(params, socketTimeout);
			HttpConnectionParams.setTcpNoDelay(params, true);
			HttpConnectionParams.setConnectionTimeout(params, connectTimeout);
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			KeyStore trustStore = null;
			try {
				trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
				trustStore.load(null, null);
				SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
				sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				SchemeRegistry schReg = new SchemeRegistry();

				schReg.register(new Scheme("http", PlainSocketFactory
						.getSocketFactory(), 80));
				schReg.register(new Scheme("https", sf, 443));
				ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
						params, schReg);
				customerHttpClient = new DefaultHttpClient(conMgr, params);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return customerHttpClient;
	}

}
